package org.zizi.db.plan.reader;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.List;

import org.apache.log4j.Logger;
import org.zizi.convert.Converter;
import org.zizi.db.column.ColumnReader;
import org.zizi.db.plan.ResultReader;
import org.zizi.db.tool.BeanFieldReader;
import org.zizi.util.NameParser;

public class BeanResultReader<T> implements ResultReader<T>
{
	private Logger log = Logger.getLogger(BeanResultReader.class);
	
	private Class<T> type;
	private List<String> columns;
	private List<ColumnReader> readers;
	
	public BeanResultReader(Class<T> type, List<String> columns, List<ColumnReader> readers)
	{
		this.type = type;
		this.columns = columns;
		this.readers = readers;
	}
	
	public T build(ResultSet rs) throws Exception
	{
		T t = type.newInstance();
		
		//set it's field's value
		int n = columns.size();
		for (int i = 0; i < n; i++)
		{
			String column = columns.get(i);
			String name = NameParser.parse(column);
			
			if ("esqlRownum".equals(name)) continue;
			
			Field field = BeanFieldReader.getField(type, name);
			if (field == null)
			{
				log.debug("类" + type.getName() + "中不存在域" + name + "，数据库列" + column + "被忽略。");
				continue;
			}
			
			ColumnReader reader = readers.get(i);
			Object o = reader.read(rs, i + 1);
			
			Converter converter = Converter.getConverter(field.getType());
			Object r = converter.convert(o);
			
			field.setAccessible(true);
			field.set(t, r);
		}
		
		return t;
	}
}
